<?php

namespace App\Model\Service;


use App\Model\CartModel;
use Trois\Lib\Help;

class CustomerCartService extends BaseService
{
    public function list(): array
    {

        // 初始条件
        $where = [
            'cart.group_id' => $this->loginUser['group_id'],
            'cart.biz_id' => $this->loginUser['biz_id'],
            'cart.cus_id' => $this->postParams['cus_id'],
            'cart.status' => [99, '!=']
        ];


        $cart = Help::modelInvoke(CartModel::class, function (CartModel $model) use ($where) {
            $list = $model
                ->field('
                cart.cart_id
                ,cart.cart_no
                ,cart.bra_id
                ,cart.cus_id
                ,cart.appoint_date
                ,cart.appoint_time
                ,cart.end_time
                ,cart.cus_type
                ,cart.projects
                ,cart.remarks
                ,cart.add_user_id
                ,cart.add_user_name
                ,cart.status
                ,cart.order_date_id_user
                ,cart.order_date_id_dept
                ,cart.dep_amount
                ,order_user.user_name as order_user_name
                ,order_dept.dept_name as order_dept_name
                ,shop.dept_name as shop_name
                ,brand.bra_name
                ')
                ->alias('cart')
                ->join('by_crm_user as order_user', 'order_user.user_id = cart.order_date_id_user', 'left')
                ->join('by_crm_dept as order_dept', 'order_dept.dept_id = cart.order_date_id_dept', 'left')
                ->join('by_crm_dept as shop', 'shop.dept_id = cart.dept_id', 'left')
                ->join('by_crm_brand as brand', 'brand.bra_id = cart.bra_id', 'left')
                ->limit($this->postParams['limit'] * ($this->postParams['page'] - 1), $this->postParams['limit'])
                ->order('cart.cart_id', 'desc')
                ->withTotalCount()
                ->all($where)
                ->toArray(false, false);

            $total = $model->lastQueryResult()->getTotalCount();

            return [
                'total' => $total,                                                  // 总数据数
                'list' => $list,                                                    // 当前数据
                'pages' => ceil($total / $this->postParams['limit']),              // 总页数
                'page' => $this->postParams['page'],                                    // 当前所在页
                'limit' => $this->postParams['limit'],                                  // 每页数据数
            ];


        }, false);

        dd(Help::getLastSql());

        return $cart ?: [
            'total' => 0,
            'list' => [],
            'pages' => 1,
            'page' => $this->postParams['page'],
            'limit' => $this->postParams['limit'],
        ];
    }


}